import { Injectable } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Role } from '../schema/role.schema'
import { Model } from 'mongoose'
import { Rule } from '../schema/rule.schema'
import { User } from '../schema/user.schema'
import { JwtService } from '@nestjs/jwt'

@Injectable()
export class SystemService {
  constructor(
    @InjectModel(Role.name) private RoleModel: Model<Role>,
    @InjectModel(Rule.name) private RuleModel: Model<Rule>,
    @InjectModel(User.name) private UserModel: Model<User>,
    private JwtService: JwtService,
  ) {}
  // 登录
  async login(_user: User) {
    try {
      const user = await this.UserModel.findOne({
        username: _user.username,
      })
      if (!user) return { msg: '未找到用户' }
      if (!(user.password === _user.password)) return { msg: '密码错误' }
      // const token = this.JwtService.sign(user)
      let list = await  this.UserModel.find({ username: _user.username,password: _user.password }).populate('role')
      let list1 = await  this.RoleModel.find({ _id: list[0].role}).populate('rules').lean()
      const data = this.menus(list1)
      return { msg: '登录成功', list ,data}
    } catch (e) {
      console.log(e)
    }
  }

  // 注册
  async register(_user: User) {
    try {
      const user = await this.UserModel.findOne({ username: _user.username })
      if (user) return { msg: '用户已存在' }
      const res = await this.UserModel.create(_user)
      return { msg: '注册成功', data: res }
    } catch (e) {
      return { msg: '注册失败' }
    }
  }

  async getMenu(body){
    const list = await this.UserModel.find({_id:body.token}).populate('role')
    let list1 = await  this.RoleModel.find({ _id: list[0].role}).populate('rules').lean()
    const data = this.menus(list1)
    return {data}
  }

  menus(list1){
    let obj = {}
      list1[0].rules.forEach((item) => {
        obj[item['key']] = item
      })
      let data = []
      list1[0].rules.forEach((item) => {
        if (item['parentKey'] == null) {
          data.push(item)
        } else {
          if (
            obj[item['parentKey']] != null &&
            !obj[item['parentKey']]['children']
          ) {
            obj[item['parentKey']]['children'] = []
          }
          if (obj[item['parentKey']] != null) {
            obj[item['parentKey']]['children'].push(item)
          }
        }
      })
      return data
  }
  async addRule() {
    this.RuleModel.create([
      { label: '首页', key: 'home', parentKey: null },
      { label: '商户', key: 'merchant', parentKey: null },
      { label: '商品', key: 'product', parentKey: null },
      { label: '订单', key: 'order', parentKey: null },
      { label: '运营', key: 'operation', parentKey: null },
      { label: '财务', key: 'fiance', parentKey: null },
      { label: '系统', key: 'system', parentKey: null },
      { label: '工作台', key: 'home-workbenth', parentKey: 'home' },
      { label: '工作台', key: 'workbenth', parentKey: 'home-workbenth' },
      { label: '商户管理', key: 'merchant-admin', parentKey: 'merchant' },
      { label: '品牌管理', key: 'brand-admin', parentKey: 'merchant' },
      { label: '店铺管理', key: 'shop-admin', parentKey: 'merchant' },
      { label: '分区管理', key: 'area-admin', parentKey: 'merchant' },
      { label: '外卖平台绑定', key: 'platform-bind', parentKey: 'merchant' },
      { label: '打印机绑定', key: 'printer-bind', parentKey: 'merchant' },
      { label: '商户列表', key: 'merchant-list', parentKey: 'merchant-admin' },
      { label: '商户信息', key: 'merchant-info', parentKey: 'merchant-admin' },
      { label: '品牌列表', key: 'brand-list', parentKey: 'brand-admin' },
      { label: '店铺列表', key: 'shop-list', parentKey: 'shop-admin' },
      { label: '店铺信息', key: 'shop-info', parentKey: 'shop-admin' },
      { label: '分区管理', key: 'area-list', parentKey: 'area-admin' },
      {
        label: '外卖绑定列表',
        key: 'platform-bind-list',
        parentKey: 'platform-bind',
      },
      { label: '打印机列表', key: 'printer-list', parentKey: 'printer-bind' },
      { label: '商品管理', key: 'product-admin', parentKey: 'product' },
      { label: '商品列表', key: 'product-list', parentKey: 'product-admin' },
      {
        label: '商品分类',
        key: 'product-classify',
        parentKey: 'product-admin',
      },
      { label: '套餐设置', key: 'set-menu', parentKey: 'product-admin' },
      { label: '订单管理', key: 'order-admin', parentKey: 'order' },
      { label: '订单列表', key: 'order-list', parentKey: 'order-admin' },
      {
        label: '预定订单列表',
        key: 'pre-order-list',
        parentKey: 'order-admin',
      },
      { label: '订单管理', key: 'orders-admin', parentKey: 'order-admin' },
      { label: '运营分析', key: 'operation-analyse', parentKey: 'operation' },
      {
        label: '客户分析',
        key: 'client-analyse',
        parentKey: 'operation-analyse',
      },
      {
        label: '运营分析',
        key: 'operations-analyse',
        parentKey: 'operation-analyse',
      },
      {
        label: '客单分析',
        key: 'per-customer-analyse',
        parentKey: 'operation-analyse',
      },
      {
        label: '产品分析',
        key: 'product-analyse',
        parentKey: 'operation-analyse',
      },
      {
        label: '产品分类销售分析',
        key: 'product-classify-analyse',
        parentKey: 'operation-analyse',
      },
      { label: '收支管理', key: 'income-admin', parentKey: 'fiance' },
      { label: '门店销售报表', key: 'shop-income', parentKey: 'income-admin' },
      { label: '店铺对账单', key: 'shop-bill', parentKey: 'income-admin' },
      {
        label: '销售收入明细',
        key: 'market-income',
        parentKey: 'income-admin',
      },
      { label: '日报管理', key: 'daily-admin', parentKey: 'fiance' },
      { label: '门店销售日报', key: 'shop-daily', parentKey: 'daily-admin' },
      { label: '权限设置', key: 'rule-admin', parentKey: 'system' },
      { label: '角色管理', key: 'role-admin', parentKey: 'rule-admin' },
      { label: '账户管理', key: 'user-admin', parentKey: 'rule-admin' },
      { label: '打印设置', key: 'print-set', parentKey: 'system' },
      { label: '打印模型', key: 'print-template', parentKey: 'printer-set' },
    ])
  }

  async getRules(rules) {
    try {
      const res = await this.RuleModel.find({ _id: rules }).lean()
      let obj = {}
      res.forEach((item) => {
        obj[item.key] = item
      })
      let data = []
      res.forEach((item) => {
        if (item['parentKey'] == null) {
          data.push(item)
        } else {
          if (
            obj[item['parentKey']] != null &&
            !obj[item['parentKey']]['children']
          ) {
            obj[item['parentKey']]['children'] = []
          }
          if (obj[item['parentKey']] != null) {
            obj[item['parentKey']]['children'].push(item)
          }
        }
      })
      return { msg: '获取成功', data }
    } catch (e) {
      console.log(e)
      return { msg: '获取失败' }
    }
  }

  // 获取角色和规则列表
  async getRoleList(id) {
    let data = await this.RoleModel.find({ _id: id.name }).populate('rules')
    return { msg: '获取成功', data }
  }
  // 获取角色列表
  async getAllRole(name) {
    try {
      if (name) {
        const res = await this.RoleModel.find({ name })
        return { msg: '获取成功', data: res }
      } else {
        const res = await this.RoleModel.find()
        return { msg: '获取成功', data: res }
      }
    } catch (e) {
      return { msg: '获取失败' }
    }
  }
  // 添加角色
  async addRole(body) {
    try {
      const res = await this.RoleModel.create(body)
      return { msg: '添加成功', data: res }
    } catch (e) {
      return { msg: '添加失败' }
    }
  }
  // 修改角色
  async updateRole(body) {
    console.log(body)
    const { _id } = body
    try {
      const res = await this.RoleModel.findByIdAndUpdate(_id, body)
      return { msg: '修改成功', data: res }
    } catch (e) {
      return { msg: '修改失败' }
    }
  }
  // 删除角色
  async deleteRole(_id) {
    try {
      const res = await this.RoleModel.findByIdAndDelete(_id)
      return { msg: '删除成功', data: res }
    } catch (e) {
      return { msg: '删除失败' }
    }
  }
  // 获取用户
  async getUserList(name) {
    if (name.name!='') {
      const res = await this.UserModel.find({ $or : [
        {username:name.name},
        {phone:name.name}
      ]}).populate('role')
      
      return { msg: '获取成功', data: res }
    }else {
      const res = await this.UserModel.find().populate('role')
      return { msg: '获取成功', data: res }
    }
  }
  // 修改用户
  async updateUser(body) {
    console.log(body)
    const { _id} = body
    try {
      const res = await this.UserModel.findByIdAndUpdate(_id, body)
      return { msg: '更新成功', data: res }
    } catch (e) {
      return { msg: '更新失败' }
    }
  }
}